import { resMgr } from "../Manager/ResMgr";
import { CycleLifeFlag } from "./CycleLifeFlag";

export class BaseRes {

    private cache: Map<string, number> = new Map<string, number>();
    private target: any = null

    constructor(target: cc.Object) {
        this.target = target
    }

    private targetActive() {
        return (this.target.checkCycleLifeFlag(CycleLifeFlag.Opening) && !this.target.checkCycleLifeFlag(CycleLifeFlag.Destroy))
    }

    public load<T extends cc.Asset>(assetPath: string, type: typeof cc.Asset): Promise<T> {
        return new Promise((resolve, reject) => {
            resMgr.load(assetPath, type).then((res: T) => {
                if (res) {
                    if (this.targetActive()) {
                        this.addAssetRef(assetPath, res)
                        resolve(res)
                    } else {
                        res.decRef()
                    }
                }
            })
        })
    }

    private addAssetRef(key: string, res: cc.Asset): void {
        let count = this.cache.get(key)
        count = count ? count + 1 : 1
        this.cache.set(key, count)
    }

    public destroy(): void {
        if (this.cache) {
            this.cache.forEach((count, url) => {
                resMgr.releaseByRecord(url, count)
            });
            this.cache.clear()
        }
    }
}